package com.wind.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import com.wind.entity.FileContent;
import com.wind.entity.FileList;
import com.wind.model.FileDetail;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: Tools
 * @Description: TODO
 * @Author: wind
 * @Date: 2018/8/9 下午3:04
 */
public class Tools {
    public static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    public static String accessKeyId = "LTAIH0ByAy0xZLOA";
    public static String accessKeySecret = "bcCBy8KkO0G4ZiX35yxPD2BPjxwbIP";
    public static String bucketName = "voicecard";

    public static String appKey ="SFSa7v9nXuSNJhs4";


//    public static String key = "s1575614484665_rec.wav";
//    public static String uploadFile = "D:/s1575614484665_rec.wav";


    public static String getVoiceContent(String uploadFilePath,String downloadFileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, downloadFileName);
            // The local file to upload---it must exist.
            uploadFileRequest.setUploadFile(uploadFilePath);
            // Sets the concurrent upload task number to 5.
            uploadFileRequest.setTaskNum(5);
            // Sets the part size to 1MB.
            uploadFileRequest.setPartSize(1024 * 1024 * 1);
            // Enables the checkpoint file. By default it's off.
            uploadFileRequest.setEnableCheckpoint(true);

            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);

            CompleteMultipartUploadResult multipartUploadResult =
                    uploadResult.getMultipartUploadResult();
            System.out.println(multipartUploadResult.getETag());

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }

        String fileLink = "https://voicecard.oss-cn-shanghai.aliyuncs.com/"+downloadFileName;
        FileTransJavaDemo demo = new FileTransJavaDemo(accessKeyId, accessKeySecret);
        // 第一步：提交录音文件识别请求，获取任务ID用于后续的识别结果轮询
        String taskId = demo.submitFileTransRequest(appKey, fileLink);
        if (taskId != null) {
            System.out.println("录音文件识别请求成功，task_id: " + taskId);
        }
        else {
            System.out.println("录音文件识别请求失败！");
            return "";
        }
        // 第二步：根据任务ID轮询识别结果
        String returnStr = demo.getFileTransResult(taskId);
        return returnStr;
    }

    public static List<FileContent>getFileContent(String filePath){
        List<FileContent> list = new ArrayList<>();
        File file = new File(filePath);
        //定义一个fileReader对象，用来初始化BufferedReader
        FileReader reader = null;
        try {
            reader = new FileReader(file);
            //new一个BufferedReader对象，将文件内容读取到缓存
            BufferedReader bReader = new BufferedReader(reader);
            //定义一个字符串缓存，将字符串存放缓存中
            String s = "";
            //逐行读取文件内容，不读取换行符和末尾的空格
            while ((s =bReader.readLine()) != null) {
                list.add(new FileContent(s));
            }
            bReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static List<FileList> getFileList(String path){
        List<FileList> list = new ArrayList<>();
        File file = new File(path);
        if(file.isDirectory()){
            FilenameFilter ff = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    if(name.lastIndexOf('.')>0) {
                        // get last index for '.' char
                        int lastIndex = name.lastIndexOf('.');
                        // get extension
                        String str = name.substring(lastIndex).toLowerCase();
                        // match path name extension
                        if(".txt".equals(str)) {
                            return true;
                        }
                    }
                    return false;
                }
            };
            String []files = file.list(ff);
            for(int i=0;i<files.length;i++){
                list.add(new FileList(i+1,files[i]));
            }
        }
        return list;
    }

    public static Map<String,Object> getSuccRespMap(){
        Map<String,Object> map = new HashMap<>(16);
        map.put("resultCode","0");
        map.put("resultMsg","操作成功");
        return map;
    }

    public static Map<String,Object> getSuccRespMap(String msg){
        Map<String,Object> map = getSuccRespMap();
        map.put("resultMsg",msg);
        return map;
    }

    public static Map<String,Object> getSuccRespMap(String msg,Object data){
        Map<String,Object> map = getSuccRespMap();
        map.put("resultMsg",msg);
        map.put("data",data);
        if(data instanceof List){
            map.put("total",((List) data).size());
        }
        return map;
    }

    public static void main(String args[]) throws Exception {
       String test = Tools.getVoiceContent("D:/m1575963331949_rec.wav","m1575963331949_rec.wav");
        System.out.println("翻译过来的是:"+test);
        System.out.println("翻译过来的是:"+test);
    }
}